import { ref } from "vue"
import { defineStore } from "pinia"

export const useHomeviewStore = defineStore("homeview", () => {
  // 状态
  const menuActive = ref(false)
  const isDayTheme = ref(true)
  const themeButtonText = ref("爪间日光")
  const themeIcon = ref("fas fa-moon")
  const isLoading = ref(false)
  const contentRef = ref(null)
  const showLoginDialog = ref(false)
  const currentDayScheme = ref(1)
  const isBlogLoading = ref(false)
  const tipInfo = ref({
    isShow: false,
    durationTime: 1500,
    msg: "",
    level: "",
  })
  const waitTime = ref(1500)

  // 页面跳转loading状态
  const pageLoading = ref({
    visible: false,
    loading: true,
  })

  /**
   *
   * @param {Object} param
   */
  const switchTipStatus = (param) => {
    tipInfo.value.msg = param.msg
    tipInfo.value.level = param.level
    tipInfo.value.isShow = true
    setTimeout(() => {
      tipInfo.value.isShow = false
      tipInfo.value.msg = ""
      tipInfo.value.level = ""
    }, tipInfo.value.durationTime)
  }

  // 显示页面loading
  const showPageLoading = () => {
    pageLoading.value.visible = true
    pageLoading.value.loading = true
  }

  // 隐藏页面loading
  const hidePageLoading = () => {
    pageLoading.value.loading = false
  }

  // 页面loading动画完成回调
  const onPageLoadingComplete = () => {
    pageLoading.value.visible = false
  }

  const toggleTheme = () => {
    isDayTheme.value = !isDayTheme.value
    updateThemeUI()

    // 保存主题偏好
    localStorage.setItem("theme", isDayTheme.value ? "day-theme" : "night-theme")
  }

  // 更新主题UI
  const updateThemeUI = () => {
    themeButtonText.value = isDayTheme.value ? "爪间日光" : "一川星语"
    themeIcon.value = isDayTheme.value ? "fas fa-moon" : "fas fa-sun"
    document.body.className = isDayTheme.value ? "day-theme" : "night-theme"
  }

  // 初始化主题
  const initTheme = () => {
    const savedTheme = localStorage.getItem("theme")
    if (savedTheme === "night-theme") {
      isDayTheme.value = false
    } else {
      isDayTheme.value = true
    }
    updateThemeUI()
  }

  return {
    menuActive,
    isDayTheme,
    themeButtonText,
    themeIcon,
    isLoading,
    contentRef,
    showLoginDialog,
    currentDayScheme,
    isBlogLoading,
    tipInfo,
    waitTime,
    pageLoading,
    switchTipStatus,
    showPageLoading,
    hidePageLoading,
    onPageLoadingComplete,
    toggleTheme,
    initTheme,
    updateThemeUI,
  }
})
